//
//  STUserManger.m
//  GodHorses
//
//  Created by Mac on 2017/11/25.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "STUserManger.h"

@implementation STUserManger
+ (STUserManger *)defult{
    static STUserManger * deflut = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        deflut = [STUserManger new];
    });
    return deflut;
}

- (void)removeUserPreferce{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:TM_USER_JSON_KEY];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)updateUserModel:(BBUserModel *)userModel{
    NSString * invite = userModel.invite_bg;
    if (!invite.length) {
        invite = [BBSystemManger manger].invite_bg;
    }
    [[SDWebImageManager sharedManager] cachedImageExistsForURL:[NSURL URLWithString:invite] completion:^(BOOL isInCache) {
        
    }];
    if (userModel) {
        BBUserModel * loginedUser = [self loginedUser];
        if (loginedUser) {
            //不更新token
            userModel.password = loginedUser.password;
            userModel.openid = loginedUser.openid;
        }
        //加载背景图
        [[SDWebImageManager sharedManager] cachedImageExistsForURL:[NSURL URLWithString:userModel.share_news_bg] completion:^(BOOL isInCache) {
            
        }];
        //加载分享
        [[SDWebImageManager sharedManager] cachedImageExistsForURL:[NSURL URLWithString:userModel.invite_bg] completion:^(BOOL isInCache) {
            
        }];
        NSString * userString = userModel.mj_JSONString;
        [[NSUserDefaults standardUserDefaults] setValue:userString forKey:TM_USER_JSON_KEY];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }else{
        NSLog(@"user 不能为空");
    }
}
- (BBUserModel *)loginedUser{
    NSString * jsonStr = [[NSUserDefaults standardUserDefaults] valueForKey:TM_USER_JSON_KEY];
    NSData * data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    if (jsonStr.length) {
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        BBUserModel *loginedUser = [BBUserModel mj_objectWithKeyValues:dic];
        return loginedUser;
    }
    return nil;
}
@end

